﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.Samples.Location;


namespace test
{
    public class GPS
    {
        private Gps _gps = new Gps();
        private GpsPosition _currentPosition = null;
        private GpsDeviceState device =null;
      
        ~GPS()
        {
            SetRadioOff();
        }
        public GPSData CurrentLocation
        {
            get
            {
                if (_currentPosition != null && _currentPosition.LatitudeValid && _currentPosition.LongitudeValid && _currentPosition.TimeValid)
                {
                    return new GPSData() { Latitude = _currentPosition.Latitude, Longitude = _currentPosition.Longitude, Time = _currentPosition.Time };
                }
                else
                {
                    return GPSData.Empty;
                }
            }
        }

        private void _gps_LocationChanged(object sender, Microsoft.WindowsMobile.Samples.Location.LocationChangedEventArgs args)
        {
            _currentPosition = args.Position;


        }

        #region IPositionOriginator Members

        public bool GetRadioStatus()
        {
            device =_gps.GetDeviceState();

            if (device.DeviceState == GpsServiceState.On)
                return true;
            else return false;

        }

        public int SetRadioOn()
        {
            try
            {
                _gps.LocationChanged += new Microsoft.WindowsMobile.Samples.Location.LocationChangedEventHandler(_gps_LocationChanged);

                if (!_gps.Opened)
                {
                    _gps.Open();

                }
            }
            catch
            {
                return 1;
            }
            return 0;
        }

        public int SetRadioOff()
        {
            try
            {
                _gps.LocationChanged -= new Microsoft.WindowsMobile.Samples.Location.LocationChangedEventHandler(_gps_LocationChanged);

                if (_gps.Opened)
                {
                    _gps.Close();
                }
            }
            catch
            {
                return 1;
            }
            return 0;
        }

        public int SetRadioOn(int interval)
        {
            throw new NotImplementedException();
        }

        public int SetRadioOff(int interval)
        {
            throw new NotImplementedException();
        }

        public int DataRequest()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IGPSOriginator Members

        public GPSData GetData()
        {
            return CurrentLocation;
        }

        #endregion
    }
}
